package com.lc.guessTheWords.rank;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

import android.os.AsyncTask;
import android.os.Message;

import com.lc.guessTheWords.core.StageManager;

public class GetMyRankAsyncTask extends AsyncTask<Integer, Integer, Integer> {
	private Integer type;

	@Override
	protected Integer doInBackground(Integer... types) {
		if (types != null && types.length > 0) {
			Integer type = types[0];
			this.type = type;
			try {
				String url = String.format("%s%s?id=%s&type=%d",
						SAEHelper.SAE_SERVER_URL, SAEHelper.GET_MY_RANK_URL,
						StageManager.instance.getMyRankID(), type);
				URL feedUrl = new URL(url);
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(feedUrl.openConnection()
								.getInputStream()));
				String result = reader.readLine();
				if (result != null) {
					return Integer.parseInt(result);
				}
				return -1;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return -1;
	}

	@Override
	protected void onPostExecute(Integer rank) {
		// // 根据本人的排名获取周围人的排名
		// if (rank != -1) {
		// int start = rank - 4;
		// start = Math.max(start, 0);
		// GetRankInRangeAsyncTask task = new GetRankInRangeAsyncTask();
		// Param param = task.new Param();
		// param.type = type;
		// param.start = start;
		// param.count = 10;
		// task.execute(param);
		// }

		if (rank != -1) {
			// 更新我的排名信息
			Message msg = new Message();
			msg.what = 1;
			msg.arg1 = rank;
			RankActivity.loadCompleteHadler.sendMessage(msg);
		}
		// 获取Top10
		SAEHelper.getTop10Rank(1);
	}
}
